//
//  VideoInfoController.swift
//  maopu
//
//  Created by 黄海波 on 2017/4/5.
//  Copyright © 2017年 maopu. All rights reserved.
// 视频详情页

import UIKit
import Masonry

class VideoInfoController: BaseViewController , WMPlayerDelegate{
    fileprivate var wmPlayer:WMPlayer!
    fileprivate var playerFrame:CGRect!
    fileprivate let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
    
    var url:String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        appDelegate.blockRotation = true
        self.initView()
    }

    open override var shouldAutorotate: Bool {
        get {
            return false
        }
    }
    
    open override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
        get {
            return .portrait
        }
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
        get{
            return .portrait
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        //获取设备旋转方向的通知,即使关闭了自动旋转,一样可以监测到设备的旋转方向
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        //旋转屏幕通知
        NotificationCenter.default.addObserver(self, selector: #selector(self.onDeviceOrientationChange(notification:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        appDelegate.blockRotation = false
        let value = UIInterfaceOrientation.portrait.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
    }
    
//    override func  shouldAutorotate() -> Bool {
//        return true
//    }
    deinit {
        self.releaseWMPlayer()
        NotificationCenter.default.removeObserver(self)
    }
    
    
    fileprivate func initView(){
        
        self.initPlayer()
    }
    
    fileprivate func initPlayer(){
        self.playerFrame = CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height - 50)
        
        self.wmPlayer = WMPlayer.init()
        self.wmPlayer.delegate = self
        self.wmPlayer.urlString = self.url
        self.wmPlayer.closeBtn.isHidden = false
        self.wmPlayer.titleLabel.text = ""
        self.wmPlayer!.playOrPauseBtn.isSelected = true
        self.view.addSubview(self.wmPlayer)
        
        self.wmPlayer.play()
        
//        wmPlayer.snp.makeConstraints { (make) in
//            make.top.equalTo(view.snp.top)
//            make.left.equalTo(view.snp.left)
//            make.right.equalTo(view.snp.right)
//            make.height.equalTo(view.snp.height)
//        }
        
        wmPlayer.mas_makeConstraints { (make) in
            make?.top.equalTo()(self.view)?.with().offset()(0)
            make?.left.equalTo()(self.view)?.with().offset()(0)
            make?.right.equalTo()(self.view)?.with().offset()(0)
            make?.height.equalTo()(self.playerFrame.size.height)
        }
    }
    
    //MARK:重置 player
    fileprivate func releaseWMPlayer(){
        if wmPlayer != nil{
            wmPlayer.pause()
            wmPlayer.removeFromSuperview()
            wmPlayer.playerLayer.removeFromSuperlayer()
            wmPlayer.player.replaceCurrentItem(with: nil)
            wmPlayer.player = nil
            wmPlayer.currentItem = nil
            wmPlayer.autoDismissTimer.invalidate()
            wmPlayer.autoDismissTimer = nil
            wmPlayer.playOrPauseBtn = nil
            wmPlayer.playerLayer = nil
            wmPlayer = nil
        }
    }
    
    //MARK:点击关闭按钮代理方法
    func wmplayer(_ wmplayer: WMPlayer!, clickedClose closeBtn: UIButton!) {
        if wmPlayer.isFullscreen{
            self.toOrientation(orientation: .portrait)
            wmPlayer.isFullscreen = false
        }else{
            self.releaseWMPlayer()
            self.navigationController?.popViewController(animated: true)
        }
    }
    //MARK:点击播放暂停按钮代理方法
    func wmplayer(_ wmplayer: WMPlayer!, clickedPlayOrPause playOrPauseBtn: UIButton!) {
        
    }
    //MARK:点击全屏按钮代理方法
    func wmplayer(_ wmplayer: WMPlayer!, clickedFullScreenButton fullScreenBtn: UIButton!) {
        if wmPlayer.isFullscreen{
//            appDelegate.blockRotation = false
//            let value = UIInterfaceOrientation.portrait.rawValue
//            UIDevice.current.setValue(value, forKey: "orientation")
            self.toOrientation(orientation: UIInterfaceOrientation.portrait)
            wmPlayer.isFullscreen = false
            
        }else{
//            appDelegate.blockRotation = true
//            let value = UIInterfaceOrientation.landscapeLeft.rawValue
//            UIDevice.current.setValue(value, forKey: "orientation")
            self.toOrientation(orientation: UIInterfaceOrientation.landscapeRight)
            wmPlayer.isFullscreen = true
        }
    }
    //MARK:单击WMPlayer的代理方法
    func wmplayer(_ wmplayer: WMPlayer!, singleTaped singleTap: UITapGestureRecognizer!) {
        
    }
    //MARK:双击WMPlayer的代理方法
    func wmplayer(_ wmplayer: WMPlayer!, doubleTaped doubleTap: UITapGestureRecognizer!) {
        
    }
    //MARK:播放失败的代理方法
    func wmplayerFailedPlay(_ wmplayer: WMPlayer!, wmPlayerStatus state: WMPlayerState) {
        Log.shared.printLog("播放失败")
    }
    //MARK:播放完毕的代理方法
    func wmplayerFinishedPlay(_ wmplayer: WMPlayer!) {
        
    }
    //MARK:准备播放的代理方法
    func wmplayerReady(toPlay wmplayer: WMPlayer!, wmPlayerStatus state: WMPlayerState) {
        
    }
    //MARK:屏幕旋转通知
    func onDeviceOrientationChange(notification:NSNotification){
        if wmPlayer == nil || wmPlayer.superview == nil{
            return
        }
        let orientation:UIDeviceOrientation = UIDevice.current.orientation
        switch orientation {
        case .portraitUpsideDown:
            Log.shared.printLog("屏幕倒立,第3个旋转方向---电池栏在下")
            wmPlayer.isFullscreen = false
            break
        case .portrait:
            Log.shared.printLog("屏幕正常竖向,第0个旋转方向---电池栏在上")
            self.toOrientation(orientation: UIInterfaceOrientation.portrait)
            wmPlayer.isFullscreen = false
            break
        case .landscapeLeft:
            Log.shared.printLog("屏幕左旋转,第2个旋转方向---电池栏在左")
            self.toOrientation(orientation: UIInterfaceOrientation.landscapeLeft)
            wmPlayer.isFullscreen = true
            break
        case .landscapeRight:
            Log.shared.printLog("屏幕右旋转,第1个旋转方向---电池栏在右")
            self.toOrientation(orientation: UIInterfaceOrientation.landscapeRight)
            wmPlayer.isFullscreen = true
            break
        default:
            break
        }
        self.setNeedsStatusBarAppearanceUpdate()
    }
    //MARK:点击进入,退出全屏,或者监测到屏幕旋转去调用的方法
    fileprivate func toOrientation(orientation:UIInterfaceOrientation){
        //获取到当前状态条的方向
        let currentOrientation:UIInterfaceOrientation = UIApplication.shared.statusBarOrientation
        if currentOrientation == orientation{
            //判断如果当前方向和要旋转的方向一致,那么不做任何操作
            return
        }
        //根据要旋转的方向,使用Masonry重新修改限制
        if orientation == UIInterfaceOrientation.portrait{
//            wmPlayer.snp.remakeConstraints { (make) in
//                make.top.equalTo(view.snp.top)
//                make.left.equalTo(view.snp.left)
//                make.right.equalTo(view.snp.right)
//                make.height.equalTo(view.snp.height)
//            }
            wmPlayer.mas_remakeConstraints({ (make) in
                make?.top.equalTo()(self.view)?.with().offset()(0)
                make?.left.equalTo()(self.view)?.with().offset()(0)
                make?.right.equalTo()(self.view)?.with().offset()(0)
                make?.height.equalTo()(self.playerFrame.size.height)
            })
        }else{
            //这个地方加判断是为了从全屏的一侧,直接到全屏的另一侧不用修改限制,否则会出错
            if currentOrientation == .portrait{
                wmPlayer.mas_remakeConstraints({ (make) in
                    make?.width.equalTo()(UIScreen.main.bounds.size.height)
                    make?.height.equalTo()(UIScreen.main.bounds.size.width)
                    make?.center.equalTo()(self.wmPlayer.superview)
                })
                
//                wmPlayer.snp.remakeConstraints({ (make) in
//                    make.width
//                })
            }
        }
        UIApplication.shared.isStatusBarHidden = false
        UIView.beginAnimations(nil, context: nil)
        //更改了状态条的方向,但是设备方向UIInterfaceOrientation还是正方向的,这就要设置给你播放视频的视图的方向设置旋转
        //给你的播放视频的view视图设置旋转
        wmPlayer.transform = CGAffineTransform.identity
        wmPlayer.transform = WMPlayer.getCurrentDeviceOrientation()
        UIView.setAnimationDuration(2.0)
        //开始旋转
        UIView.commitAnimations()
    }
    
}
